var WxParse = require('../../wxParse/wxParse.js');
var app = getApp();
Page({
  data: {
    isHasAddress: true,
    isShowModal:false,
    shopname: '',
    orderInfo: {},
    note: "",
    curCouponId:'',
    curPromotionId:'',
    ordersource:'',
    expressWayId: '',
    orderstatus:'',
    value: [0, 0, 0],
    multiIndex: [0, 0, 0],
    multiArray: [],
    showCantPickList:false,
  },
  onLoad: function (e) {
    var that = this;
    wx.getStorage({
      key: 'shopInfoname',
      success: function (res) {
        that.setData({
          shopname: res.data
        })
      }
    })
    if (wx.getStorageSync('receiverUser')){
      var reciver = wx.getStorageSync('receiverUser');
      that.setData({
        takeUser: reciver.name,
        takeUsertel: reciver.tel
      })
    }
    if (e.ordersource){
      var ordersource = e.ordersource;
      that.setData({
        ordersource: ordersource
      })
    }
  },
  onShow: function () {
    var that = this;
    if (that.data.orderstatus)return;
    that.requestpayType();
    that.setData({
      isHasunionid: app.globalData.isHasunionid
    })
    wx.getStorage({
      key: 'submitOrder',
      success: function (res) {
        console.log('订单信息',res.data);
        var orderInfo = res.data;
        var expressWayId='',expressWayname='';
        if (that.data.expressWayId == '') {
          expressWayId = res.data.expressWay ? res.data.expressWay[0].id : '';
          expressWayname = res.data.expressWay ? res.data.expressWay[0].name : '';
        } else {
          expressWayId = that.data.expressWayId;
          expressWayname = that.data.expressWayname;
        }
        console.log(expressWayname)
        if (!that.data.remarkExtra){
          var remarkExtra = res.data.remarkExtra;
          if (remarkExtra) {
            for (var i = 0; i < remarkExtra.length; i++) {
              remarkExtra[i].id = i;
              remarkExtra[i].value = '';
            }
            that.setData({
              remarkExtra: remarkExtra
            })
          }else{
            that.setData({
              remarkExtra: []
            })
          }
        }
        var orderInfo = res.data;
        that.setData({
          orderInfo: orderInfo,
          orderInfoCopy: app.deepClone(orderInfo),
          satisfySend: parseFloat(orderInfo.satisfySend),
          expressWayId: expressWayId,
          expressWayname: expressWayname,
          addressInfo: orderInfo.address,
          cardNum: orderInfo.idcard,
          sumTotal: orderInfo.total,
          postTotal: orderInfo.postTotal,
          goodPostTotal: orderInfo.total,
          curCouponId: orderInfo.coupon[0].id,
          curCouponInfo: orderInfo.coupon[0],
          storeGoodsLimit: orderInfo.storeGoodsLimit,  //是否开启门店自提限制
       
        })
        that.calculateDiscounts();
        if (expressWayId==2){
          // console.log("门店自取");
          if (that.data.storeGoodsLimit == 1 && orderInfo.noStoreGoodsData.length > 0){
            that.setData({
              showCantPickList:true
            })
          }
          that.getLocation();

        }
        if (expressWayId == 1) {
          console.log("商家配送");
          that.requestDelivery();
        }else{
          that.getTotalprice();
        }
        
      }
    })
    wx.getStorage({
      key: 'delCart',
      success: function (res) {
        console.log(res);
        that.setData({
          cartids: res.data
        })
      }
    })
  },
  //计算优惠券和促销信息
  calculateDiscounts(){
    var orderInfo=this.data.orderInfo;
    var that=this;
    // 默认选择优惠券
    var coupon = orderInfo.coupon ? orderInfo.coupon : [];
    if (coupon.length > 0) {
      for (var i = 1; i < coupon.length; i++) {
        coupon[i].value = parseFloat(coupon[i].value);
        var remainTime = (new Date(coupon[i].end).getTime() - new Date(coupon[i].start).getTime()) / 1000;
        coupon[i].remainTime = parseInt(remainTime);
      }
      console.log(coupon);
      var newCoupon = coupon.concat();
      newCoupon = newCoupon.sort(sortValue('value', 'remainTime'));
      console.log(newCoupon)
      that.setData({
        curCouponId: newCoupon[0].id,
        curCouponInfo: newCoupon[0]
      })
    }else{
      that.setData({
        curCouponId:0,
        curCouponInfo: ''
      })
    }
    if (that.data.curCouponInfo) {
      that.confirmChooseCoupon();
    }
    // 默认选中满减促销
    var fullAct = orderInfo.fullAct ? orderInfo.fullAct : [];
    if (fullAct.length > 0) {
      for (var i = 0; i < fullAct.length; i++) {
        if (fullAct[i].type == 4) {
          fullAct[i].value = orderInfo.postTotal;
        }
        fullAct[i].value = parseFloat(fullAct[i].value);
      }
      fullAct = fullAct.sort(sortValue('value'));
      that.setData({
        curPromotionId: fullAct[0].id,
        curPromotionInfo: fullAct[0]
      })
      console.log(fullAct);
    }else{
      that.setData({
        curPromotionId: 0,
        curPromotionInfo: ''
      })
    }
    if (that.data.curPromotionInfo) {
      that.confirmChoosePromotion();
    }
    that.getTotalprice();
  },
  // 选择门店更新订单信息
  selectStore() {
    wx.showLoading({
      title: '正在获取门店信息',
    })
    var that = this;
    var orderInfo = that.data.orderInfo;
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_select_store_goods_list',
        goodsData: JSON.stringify(orderInfo.goodsData),
        id: that.data.receiveStore
      },
      success: function (res) {
        console.log('选择门店更新信息', res.data);
        if (res.data.ec == 200) {
          var goodsTotal=0;
          for (let good of res.data.data.goodsData) {
            if (good.canBuy == 1) {  
              goodsTotal = goodsTotal + parseFloat(good.price)*good.num 
            }
          }
          console.log('商品总价', goodsTotal);
         
          orderInfo.goodsData = res.data.data.goodsData;
          orderInfo.coupon = res.data.data.coupon;
          orderInfo.fullAct = res.data.data.fullAct;
          orderInfo.goodsTotal = goodsTotal.toFixed(2);
          that.setData({
            orderInfo: orderInfo
          });
          that.calculateDiscounts();
          
        } else {
          console.log(res.data)
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  
  //获得商家配送的运费数据
  requestDelivery:function(){
    var that = this;
    var orderInfo = that.data.orderInfo;
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_shop_send_price',
        tid: orderInfo.tid,
        addrid: orderInfo.address.id
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          that.setData({
            needSum: res.data.data.needSum,
            deliveryMoney: res.data.data.price,
          });
          that.getTotalprice();
        } else {
          console.log(res.data)
          that.setData({
            payType: []
          })
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  requestpayType: function () {
    var that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true,
      time: 100000
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_pay_cfg'
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var payWay = that.data.payWay;
          if (!payWay){
            payWay = res.data.data ? res.data.data[0].type : 1
          }
          that.setData({
            payType: res.data.data,
            payWay: payWay
          })
          that.payWaychange(payWay);
        } else {
          console.log(res.data)
          that.setData({
            payType: []
          })
          // app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  payRadioChange: function (e) {
    var that = this;
    var payWay = e.detail.value;
    that.payWaychange(payWay);
  },
  payWaychange: function (payWay){
    var that = this;
    var payType = that.data.payType ? that.data.payType:[];
    console.log(payType)
    var sumTotal = parseFloat(that.data.sumTotal);
    var payTypeNote = '', balance = 0;
    if (payWay == 6){
      payWay = 3;
    }
    for (let i = 0; i < payType.length; i++) {
      if (payWay == payType[i].type) {
        payTypeNote = payType[i].typeNote;
        if (payWay == 3) {
          balance = parseFloat(payType[i].balance);
        }
      }
    }
    var remainTotal = 0;
    if ((payWay == 3 || payWay == 6) && balance < sumTotal) {
      payWay = 6;
      payTypeNote = "微信支付+余额抵扣";
      remainTotal = (sumTotal - balance).toFixed(2);
    }
    this.setData({
      payWay: payWay,
      payTypeNote: payTypeNote,
      remainBalance: balance,
      remainTotal: remainTotal
    })
    console.log(remainTotal + '--' + balance + '--'+payTypeNote + '--' + payWay);
  },
  bindStoreChange:function(e){
    this.setData({
      storeIndex: e.detail.value
    })
    console.log(this.data.storeIndex);
  },
  toRecharge: function () {
    wx.navigateTo({
      url: '/subpages/walletRecharge/walletRecharge',
    })
  },
  switchChange: function (e) {
    console.log('switch 发生 change 事件，携带值为', e.detail.value)
  },
  chooseAddress: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var orderStatus = that.data.orderstatus;
    console.log(orderStatus);
    if (!orderStatus){}else{return;}
    console.log(type);
    wx.navigateTo({
      url: '/subpages/addressManage/addressManage?type=' + type
    })
  },
  noteChange: function (e) {
    this.setData({
      note: e.detail.value
    })
  },
  cardChange:function(e){
    this.setData({
      cardNum: e.detail.value
    })
  },
  takeUserChange: function (e) {
    this.setData({
      takeUser: e.detail.value
    })
  },
  takeUsertelChange: function (e) {
    this.setData({
      takeUsertel: e.detail.value
    })
  },
  // 配送方式切换
  expressWayChange: function (e) {
    console.log(e.detail.value);
    var that = this;
    var expressWay = that.data.orderInfo.expressWay;
    var id = e.detail.value;
    var expressWayname = '';
    for (var i = 0; i < expressWay.length; i++) {
      if (expressWay[i].id == id) {
        expressWayname = expressWay[i].name;
      }
    }
    
    if (this.data.storeGoodsLimit==1&&this.data.expressWayId == 2&&id!=2){  //如果由商家配送方式修改为其他方式
      this.setData({
        orderInfo: app.deepClone(this.data.orderInfoCopy)
      })
      console.log('如果由商家配送方式修改为其他方式',this.data.orderInfo);
      that.calculateDiscounts();
    }
    if (id == 1) {
      app.errorTip(that, "请点击蓝字查看配送范围及价格", 2000);
    } else if (id == 2) {
      if (this.data.storeGoodsLimit == 1 &&that.data.orderInfo.noStoreGoodsData.length>0){
        that.setData({
          showCantPickList:true
        })
      }
      that.getLocation();   
    }
    that.setData({
      expressWayId: id,
      expressWayname: expressWayname
    });
    console.log(that.data.expressWayname);
    if (id == 1) {
      console.log("商家配送");
      that.requestDelivery();
    }else{
      that.getTotalprice();
    }
  },
  getLocation: function (e) {
    var that = this;
    console.log('获取位置信息')
    if (app.globalData.location){
      that.setData(app.globalData.location)
      that.requestStore();
    }else{
      wx.showLoading({
        title: '正在获取您的位置',
      })
      wx.getLocation({
        success: function (res) {
          console.log(res);
          that.setData({
            lat: res.latitude,
            lng: res.longitude
          })
          var location = {
            lat: res.latitude,
            lng: res.longitude
          }
          app.globalData.location = location;
          that.requestStore();
        },
        fail: function () {
          wx.getSetting({
            success: (res) => {
              if (!res.authSetting['scope.userLocation']) {
                that.setData({
                  isShowsetting: true
                })
              }else{
                app.errorTip(that, "无法获取您的当前定位地址，请打开定位权限", 2000);
                that.requestStore();
              }
            }
          })
        },
        complete: function () {
          wx.hideLoading();
        }
      })
    }
  },
  hideSetting: function() {
    var that = this;
    that.setData({
      isShowsetting: false
    })
    that.requestStore();
  },
  openSetting: function() {
    var that = this;
    that.hideSetting();
    wx.openSetting({
      success: (res) => {
        res.authSetting = {
          "scope.userLocation": true
        }
        that.getLocation();
      },
      fail: function (res) {
        console.log(res);
      }
    })
  },
  requestStore:function(){
    var that = this;
    var orderInfo = this.data.orderInfo;
    var data = {
      map: 'applet_get_receive_store_new',
      lat: that.data.lat ? that.data.lat:0,
      lng: that.data.lng ? that.data.lng:0,
      tid: orderInfo.tid
    };
    if (this.data.storeGoodsLimit==1){
      data.goodsData= JSON.stringify(orderInfo.goodsData);
    }
    console.log(data);
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          console.log('可自提门店信息',res.data.data);
          if(res.data.data.data[0].id>0){
            var Data = res.data.data;
            var value = that.data.value;
            var multiIndex = that.data.multiIndex;
            var curStoreid = that.data.curStoreid;
            if (!curStoreid){
              var oneId = Data.oneId, twoId = Data.twoId, threeId = Data.threeId;
            }else{
              var oneId = curStoreid.oneId, twoId = curStoreid.twoId, threeId = curStoreid.threeId;
            }
            for(var i=0;i<Data.data.length;i++){
              if (oneId == Data.data[i].id ){
                  value[0] = i;
                  multiIndex[0] = i;
                  for (var j = 0; j < Data.data[i].submenu.length;j++){
                    if (twoId == Data.data[i].submenu[j].id){
                      value[1] = j;
                      multiIndex[1] = j; 
                      for (var h = 0; h < Data.data[i].submenu[j].submenu.length; h++) {
                        if (threeId == Data.data[i].submenu[j].submenu[h].id) {
                          value[2] = h;
                          multiIndex[2] = h; 
                        }
                      }
                    }
                  }
              }
            }
            that.setData({
              value : value,
              receiveStore: Data.threeId,
              multiIndex: multiIndex
            });
            that.defalueData(Data.data);
          }else{
            that.setData({
              storeArr: res.data.data.data,
              storeIndex: 0,
              receiveStore: res.data.data.data[0].id
            })
          }
          if (that.data.storeGoodsLimit==1){
            that.selectStore();
          }
        } else {
          console.log(res.data)
          app.errorTip(that, res.data.em, 2000);
        }
      },
      fail(res){
        console.log('获取门店列表失败',res)
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  defalueData: function (data) {
    var that = this;
    var value = that.data.value;
    var multiIndex = that.data.multiIndex;
    var allData = data;
    // var multiArray = that.data.multiArray;
    var multiArray = [];
    var first = [], second = [], third = [];
    for (var i = 0; i < allData.length; i++) {
      first[i]={
        id: allData[i].id,
        name: allData[i].name
      } 
    };
    for (var i = 0; i < allData[multiIndex[0]].submenu.length; i++) {
      second[i] = {
        id: allData[multiIndex[0]].submenu[i].id,
        name: allData[multiIndex[0]].submenu[i].name
      } 
      console.log(allData[multiIndex[0]].submenu[i].id);
    };
    for (var i = 0; i < allData[multiIndex[0]].submenu[multiIndex[1]].submenu.length; i++) {
      third[i] = {
        id: allData[multiIndex[0]].submenu[multiIndex[1]].submenu[i].id,
        name: allData[multiIndex[0]].submenu[multiIndex[1]].submenu[i].name
      } 
    };
    multiArray.push(first);
    multiArray.push(second);
    multiArray.push(third);
    console.log(multiArray);
    that.setData({
      storeArr:data,
      multiArray: multiArray
    })
  },
  bindMultiPickerChange: function (e) {
    var that = this;
    var value = e.detail.value;
    var multiArray = that.data.multiArray;
    var curStoreid = {
      oneId: multiArray[0][value[0]].id,
      twoId: multiArray[1][value[1]].id,
      threeId: multiArray[2][value[2]].id
    };
    that.setData({
      value: value,
      curStoreid: curStoreid,
      receiveStore: multiArray[2][e.detail.value[2]].id
    });
    console.log(curStoreid);
    console.log(that.data.receiveStore);

    if (this.data.storeGoodsLimit == 1) {
      that.selectStore();//更新订单信息
    } 
    
  },
  bindMultiPickerColumnChange: function (e) {
    var that = this;
    console.log(e.detail);
    var value = that.data.value;
    var multiIndex = that.data.multiIndex;
    var allData = that.data.storeArr;
    var multiArray = that.data.multiArray;
    if (e.detail.column == 0) {
      var index = e.detail.value;
      that.setData({
        multiIndex: [index, 0, 0],
        value: [index, 0, 0]
      });
      console.log(that.data.multiArray);
      var second = [], third = [];
      for (var i = 0; i < allData[index].submenu.length; i++) {
        second[i] = {
          id: allData[index].submenu[i].id,
          name: allData[index].submenu[i].name
        } 
      };
      for (var i = 0; i < allData[index].submenu[0].submenu.length; i++) {
        third[i] = {
          id: allData[index].submenu[0].submenu[i].id,
          name: allData[index].submenu[0].submenu[i].name
        } 
      };
      multiArray[1] = second;
      multiArray[2] = third;
      that.setData({
        multiArray: multiArray
      })
    }
    if (e.detail.column == 1) {
      var index = e.detail.value;
      var multiIndex = that.data.multiIndex;
      console.log(multiIndex);
      value[1] = index;
      value[2] = 0;
      that.setData({
        value: value
      });
      console.log(that.data.value);
      var third = [];
      for (var i = 0; i < allData[multiIndex[0]].submenu[index].submenu.length; i++) {
        third[i] = {
          id: allData[multiIndex[0]].submenu[index].submenu[i].id,
          name: allData[multiIndex[0]].submenu[index].submenu[i].name
        } 
      };
      multiArray[2] = third;
      that.setData({
        multiArray: multiArray
      })
    }
    if (e.detail.column == 2) {
      value[2] = e.detail.value;
      that.setData({
        value: value
      });
    }
  },
  submitOrder: function () {
    var that = this;
    app.getSubId(that, 'applet_order_confirm','toSubmitOrder');
  },
  toSubmitOrder:function(){
    var that = this;
    var tradetype = that.data.orderInfo.tradeType;
    var data = {};
    data.map = 'applet_order_confirm';
    data.tid = that.data.orderInfo.tid;
    data.payType = that.data.payWay;
    data.note = that.data.note ? that.data.note : '';

    var ordersource = that.data.ordersource;
    if (ordersource == 'cartorder') {
      if (this.data.storeGoodsLimit == 1 && that.data.expressWayId == 2) {  //门店自取限制开启，并且选择门店自取
        var goodsData = [];
        var cartids = [];
        for (let good of that.data.orderInfo.goodsData) {
          if (good.canBuy == 1) {
            cartids.push(good.cartId);
            goodsData.push(good);
          }
        }
        data.cartids = cartids.join(',');
        data.goodsData = JSON.stringify(goodsData);
      } else {
        data.cartids = that.data.cartids;
      }

    }
    if (that.data.orderInfo.needAddress == 1) {
      data.postType = parseInt(that.data.expressWayId);
      data.postFee = that.data.orderInfo.postTotal;
      if (that.data.addressInfo.id) {
        data.addrid = that.data.addressInfo.id;
      } else {
        data.addrid = "";
      }
      if (data.postType == 2) {
        var storeIndex = that.data.storeIndex;
        var storeArr = that.data.storeArr;
        data.receiverName = that.data.takeUser ? that.data.takeUser : '';
        data.receiverPhone = that.data.takeUsertel ? that.data.takeUsertel : '';
        data.receiveStore = that.data.receiveStore ? that.data.receiveStore : ''

        if (data.receiverName == '') {
          app.errorTip(that, "请输入取货人姓名", 2000);
          return;
        }
        if (!data.receiverPhone) {
          app.errorTip(that, "请输入电话或手机号", 2000);
          return;
        }
        if (!data.receiveStore) {
          app.errorTip(that, "请选择自取门店", 2000);
          return;
        }
        var receiverUser = {
          name: data.receiverName,
          tel: data.receiverPhone
        }
        wx.setStorageSync('receiverUser', receiverUser)
      } else {
        if (that.data.addressInfo.id) {
          data.addrid = that.data.addressInfo.id;
        } else {
          data.addrid = "";
        }
        if (!data.addrid) {
          app.errorTip(that, "请选择收货地址", 2000);
          return;
        }
      }
    }
    if (that.data.orderInfo.global > 0) {
      data.idcard = that.data.cardNum;
      if (data.idcard) {
        console.log("全球购");
      } else {
        app.errorTip(that, "身份证号不能为空", 2000);
        return false;
      }
    }
    if (that.data.chooseCoupon) {
      data.yhqid = that.data.chooseCoupon.id;
    }
    if (that.data.choosePromotion) {
      data.cxid = that.data.choosePromotion.id;
    }
    var remarkExtra = that.data.remarkExtra;
    for (var i = 0; i < remarkExtra.length; i++) {
      if (remarkExtra[i].require) {
        if (!remarkExtra[i].value) {
          if (remarkExtra[i].type == 'time' && remarkExtra[i].date && remarkExtra[i].dateval && remarkExtra[i].timeval) {
            remarkExtra[i].value = remarkExtra[i].dateval + ' ' + remarkExtra[i].timeval;
          }
          if (remarkExtra[i].type == 'time') {
            if (!remarkExtra[i].dateval) {
              app.errorTip(that, '请选择' + remarkExtra[i].name + '的日期', 2000);
              return;
            }
            if (!remarkExtra[i].timeval) {
              app.errorTip(that, '请选择' + remarkExtra[i].name + '的时间', 2000);
              return;
            }
          } else {
            app.errorTip(that, remarkExtra[i].name + '为必填项', 2000);
            return;
          }
        }
      }
    }
    data.remarkExtra = that.data.remarkExtra;
    console.log(data);
    //发起请求，获取列表列表
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
		  console.log(res);
        if (res.data.ec == 200) {
          console.log(res.data.data);
          that.setData({
            orderstatus: res.data.data.status
          })
          if (res.data.data.status == 'dzf') {
            console.log(data.payType);
            if (data.payType == 1 || data.payType == 6 || data.payType == 5) {

              that.orderPay();
            } else {
              if (tradetype == 2) {
                wx.redirectTo({
                  url: '/subpages/groupResult/groupResult?tid=' + data.tid
                })
              } else {
                if (ordersource == 'cartorder') { //从购物车结算时，改变参数，重新请求购物车数量
                  app.globalData.requestCartNum = -1;
                }
                wx.redirectTo({
                  url: '/pages/paySuccess/paySuccess?orderid=' + data.tid
                })
              }
            }
          }else if(res.data.data.status=='zfcg'){			  
			  
			  wx.redirectTo({
			    url: '/pages/paySuccess/paySuccess?orderid=' + data.tid
			  })
		  } else {
				if (tradetype == 2) {
				  wx.redirectTo({
					url: '/subpages/groupResult/groupResult?tid=' + data.tid
				  })
				} else {
				  if (ordersource == 'cartorder') { //从购物车结算时，改变参数，重新请求购物车数量
					app.globalData.requestCartNum = -1;
				  }
				  wx.redirectTo({
					url: '/pages/paySuccess/paySuccess?orderid=' + data.tid
				  })
				}
          }
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  // 关闭不能自提商品列表
  hideCantPickList(){
    this.setData({
      showCantPickList: false
    })
  },
  orderPay: function (e) {
    var that = this;
    var tradetype = that.data.orderInfo.tradeType;
    var data = {};
    data.map = 'applet_order_pay';
    data.tid = that.data.orderInfo.tid;
    wx.hideLoading();
    //发起请求，获取列表列表
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          wx.requestPayment({
            'appId': res.data.data.appId,
            'timeStamp': res.data.data.timeStamp,
            'nonceStr': res.data.data.nonceStr,
            'package': res.data.data.package,
            'signType': res.data.data.signType,
            'paySign': res.data.data.paySign,
            'success': function (res) {
              wx.showModal({
                title: '提示',
                content: '支付成功',
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    wx.showLoading({
                      title: '加载中',
                    })
                    setTimeout(function(){
                      wx.hideLoading();
                      if (tradetype == 2) {
                        wx.redirectTo({
                          url: '/subpages/groupResult/groupResult?tid=' + data.tid
                        })
                      } else {
                        if (that.data.ordersource == 'cartorder') { //从购物车结算时，改变参数，重新请求购物车数量
                          app.globalData.requestCartNum = -1;
                        }
                        wx.redirectTo({
                          url: '/pages/paySuccess/paySuccess?orderid=' + data.tid
                        })
                      }
                    },1000)
                  }
                }
              })
            },
            'fail': function (res) {
				wx.navigateTo({
					url:'/subpages/myorder/myorder?status=nopay'
				})
            }
          });
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  showModal:function(e){
    var that = this;
    var type = e.currentTarget.dataset.type;
    var orderInfo = that.data.orderInfo;
    var couponLen = orderInfo.coupon.length;
    var fullActLen = orderInfo.fullAct.length;
    var orderStatus = that.data.orderstatus;
    if (!orderStatus) { } else { return; }
    if (type == 'coupon' && couponLen>0){
      that.setData({
        curChooseType:'coupon',
        isShowModal:true
      })
    }
    if (type == 'promotion' && fullActLen > 0) {
      that.setData({
        curChooseType: 'promotion',
        isShowModal: true
      })
    }
  },
  hideModal:function(){
    var that = this;
    that.setData({
      isShowModal:false
    })
  },
  toggleCoupon: function (e) {
    var that = this;
    var coupon = e.currentTarget.dataset.coupon;
    that.setData({
      curCouponId: coupon.id,
      curCouponInfo: coupon
    })
  },
  confirmChooseCoupon: function () {
    var that = this;
    that.setData({
      chooseCoupon: that.data.curCouponInfo,
    })
    that.hideModal();
    that.getTotalprice();
  },
  togglePromotion: function (e) {
    var that = this;
    var promotion = e.currentTarget.dataset.promotion;
    that.setData({
      curPromotionId: promotion.id,
      curPromotionInfo: promotion
    })
  },
  confirmChoosePromotion: function () {
    var that = this;
    if (!that.data.curPromotionInfo) {
      app.errorTip(that, "请选择一个优惠", 2000);
      return;
    }
    that.setData({
      choosePromotion: that.data.curPromotionInfo,
    })
    that.hideModal();
    that.getTotalprice();
  },
  getTotalprice:function(){
    var that = this;
    var orderInfo = that.data.orderInfo;
    console.log(orderInfo);
    var curTotal = that.data.orderInfo.total;
    var expressWayId = that.data.expressWayId;
    var total = parseFloat(orderInfo.goodsTotal), goodPostTotal = parseFloat(orderInfo.goodsTotal), postTotal = parseFloat(orderInfo.postTotal);
    var curPromotionInfo = that.data.curPromotionInfo;
    var curCouponInfo = that.data.curCouponInfo;
    var choosePromotion = that.data.choosePromotion;
    console.log("配送方式" + expressWayId);
    console.log(curCouponInfo);
    console.log(curPromotionInfo);
    if (expressWayId == 1){
      console.log('商家配送')
      var deliveryMoney = parseFloat(that.data.deliveryMoney);
      var needSum = that.data.needSum;
      if (needSum){
        total = total + deliveryMoney;
      }
      if (curCouponInfo) {
        var curCouponVal = curCouponInfo.value;
        console.log(curCouponVal);
        total = total - curCouponVal;
      }
      if (curPromotionInfo) {
        var curType = curPromotionInfo.type;
        var curPromotionVal = 0;
        if (curType == 4){
          if (needSum) {
            choosePromotion.value = deliveryMoney;
            curPromotionVal = deliveryMoney;
            that.setData({
              choosePromotion: choosePromotion
            })
            console.log('商家配送费免------------' + that.data.postTotal)
            console.log(that.data.choosePromotion)
          }else{
            choosePromotion.value = 0;
            curPromotionVal = 0;
            that.setData({
              choosePromotion: choosePromotion
            })
          }
        }else{
          curPromotionVal = curPromotionInfo.value;
        }
        total = total - curPromotionVal;
      }
    }
    if (expressWayId == 2) {
      console.log('门店自取方式','商品总价',total);
      
      if (curCouponInfo) {
        var curCouponVal = curCouponInfo.value;
        console.log(curCouponVal);
        total = total - curCouponVal;
      }
      if (curPromotionInfo) {
        var curType = curPromotionInfo.type;
        var curPromotionVal = 0;
        if (curType == 4) {
          choosePromotion.value = 0;
          curPromotionVal = 0;
          that.setData({
            choosePromotion: choosePromotion,
            postTotal: 0
          })
        } else {
          curPromotionVal = curPromotionInfo.value;
        }
        total = total - curPromotionVal;
      }
      console.log('优惠券减免', curCouponVal ,'促销信息',curPromotionInfo,'优惠后总价', total,);
    }
    if (expressWayId == 3) {
      console.log('快递发货')
      total = goodPostTotal + postTotal;
      if (curCouponInfo) {
        var curCouponVal = curCouponInfo.value;
        console.log(curCouponVal);
        total = total - curCouponVal;
      }
      if (curPromotionInfo) {
        var curType = curPromotionInfo.type;
        var curPromotionVal = 0;
        if (curType == 4) {
          choosePromotion.value = postTotal;
          curPromotionVal = postTotal;
          that.setData({
            choosePromotion: choosePromotion
          })
        } else {
          curPromotionVal = curPromotionInfo.value;
        }
        total = total - curPromotionVal;
      }
    }
    if (total <= 0) {
      total = 0;
    }
    that.setData({
      sumTotal: total.toFixed(2)
    })
    setTimeout(function(){
      that.payWaychange(that.data.payWay);
    },1000)
  },
  seemap: function (e) {
    var latitude = e.currentTarget.dataset.lat;
    var longitude = e.currentTarget.dataset.lng;
    var address = e.currentTarget.dataset.address;
    var name = e.currentTarget.dataset.name;
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude),
      name: name,
      address: address,
      scale: 18
    })
  },
  // 监控数据改变
  dataChange: function (e) {
    var that = this;
    var remarkExtra = that.data.remarkExtra;
    var id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    var curVal = e.detail.value;
    for (var i = 0; i < remarkExtra.length; i++) {
      if (remarkExtra[i].id == id) {
        if (remarkExtra[i].type == 'time' && remarkExtra[i].date){
          console.log("日期时间必填");
          remarkExtra[i][type] = curVal;
          if (remarkExtra[i].dateval && remarkExtra[i].timeval){
            remarkExtra[i].value = remarkExtra[i].dateval + ' ' + remarkExtra[i].timeval;
          }
        }else{
          remarkExtra[i].value = curVal;
        }
      }
    }
    that.setData({
      remarkExtra: remarkExtra
    })
    // console.log(that.data.remarkExtra);
  },
  // 上传图片
  chooseSingleImage: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#333",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage('album', id)
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera', id)
          }
        }
      }
    })
  },
  // 预览图片
  peiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = e.currentTarget.dataset.imgs;
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  //选择单图
  chooseWxImage: function (type, id) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: [type],
      success: function (res) {
        console.log(res);
        var temPath = res.tempFilePaths[0];
        that.upload_file(temPath, id);
      }
    })
  },
  // 上传单图到服务器
  upload_file: function (temPath, id) {
    var that = this;
    var remarkExtra = that.data.remarkExtra;
    wx.showLoading({
      title: '上传中',
    })
    wx.uploadFile({
      url: app.globalData.requestUrl + '?&map=applet_img_upload',
      filePath: temPath,
      name: 'image',
      success: function (res) {
        var data = JSON.parse(res.data);
        var realpath = app.globalData.domin + data.data.path;
        if (data.ec == 200) {
          for (var i = 0; i < remarkExtra.length; i++) {
            if (remarkExtra[i].id == id) {
              remarkExtra[i].img = realpath;
              remarkExtra[i].value = data.data.path;
            }
          }
          that.setData({
            remarkExtra: remarkExtra
          })
          console.log(that.data.remarkExtra);
        } else {
          wx.showModal({
            title: '提示',
            content: data.em,
            showCancel: false
          });
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  shopDetail: function (e) {
    var id = e.currentTarget.dataset.id;
    console.log(id);
    wx.navigateTo({
      url: '/subpages/storeDetail/storeDetail?id=' + id
    })
  },
  // 查看配送范围
  todeliveryArea: function () {
    var that = this;
    var postScope = that.data.orderInfo.postScope;
    // 富文本解析
    WxParse.wxParse('postScope', 'html', postScope, that, 5);
    that.showAgreement();
  },
  showAgreement: function (e) {
    var that = this;
    this.setData({
      isShowAgreement: true
    })
  },
  hideAgreement: function () {
    this.setData({
      isShowAgreement: false
    })
  },
  getunionId: function (e) {
    var that = this;
    var userdata = e.detail;
    console.log(e.detail);
    app.getUnionid(that, userdata);
  },
})
// 根据数组某个字段排序
function sortValue(property,secprop) {
  return function (a, b) {
    var value1 = a[property];
    var value2 = b[property];
    var val = value2 - value1
    if (val==0){
      val = a[secprop] - b[secprop];
    }
    return val;
  }
}